package com.eurasia.assignment.controller;

import com.eurasia.assignment.controller.dto.FileUploadResponse;
import com.eurasia.assignment.domain.FileStorage;
import com.eurasia.assignment.infrastructure.entity.FileEntity;
import com.eurasia.assignment.infrastructure.repository.FileRepository;
import com.eurasia.assignment.service.FileService;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/files")
@RequiredArgsConstructor
public class FileController {

    private final FileService fileService;
    private final FileRepository fileRepository;
    private final FileStorage fileStorage;

    @PostMapping("/upload")
    public ResponseEntity<FileUploadResponse> uploadFile(@RequestParam("file") MultipartFile file) {
        FileUploadResponse response = fileService.storeFile(file);
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/download/{fileId}")
    public ResponseEntity<Resource> downloadFile(@PathVariable Long fileId) {
        try {
            // 从数据库获取文件信息
            FileEntity fileEntity = fileRepository.findById(fileId)
                .orElseThrow(() -> new RuntimeException("文件不存在"));
                
            // 获取文件资源
            Resource resource = fileStorage.loadFileAsResource(fileEntity.getStoredFileName());
            
            // 确定文件的内容类型
            String contentType = determineContentType(resource);
            
            return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileEntity.getOriginalFileName() + "\"")
                .body(resource);
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
    
    private String determineContentType(Resource resource) {
        try {
            Path path = Paths.get(resource.getURI());
            return Files.probeContentType(path);
        } catch (IOException e) {
            return MediaType.APPLICATION_OCTET_STREAM_VALUE;
        }
    }
} 